<template>
  <div class="ai-assistant-container">
    <div class="page-header">
      <div class="header-left">
        <h1>AI备课助手</h1>
        <p class="subtitle">利用AI技术，让备课更高效、更专业</p>
      </div>
      <div class="header-actions">
        <el-button type="primary" plain @click="startNewChat" size="large">
          <el-icon><Plus /></el-icon>新会话
        </el-button>
        <el-button plain @click="showSettingsDialog = true" size="large">
          <el-icon><Setting /></el-icon>设置
        </el-button>
      </div>
    </div>

    <el-row :gutter="20" class="main-content">
      <!-- 左侧边栏 - 历史会话 -->
      <el-col :span="4" class="sidebar">
        <div class="sidebar-header">
          <h3>历史会话</h3>
          <el-button type="primary" text @click="startNewChat" size="small">
            <el-icon><Plus /></el-icon>
          </el-button>
        </div>
        <div class="history-list">
          <div
            v-for="(chat, index) in chatHistory"
            :key="index"
            class="history-item"
            :class="{ active: currentChatIndex === index }"
            @click="switchChat(index)"
          >
            <div class="history-item-title">{{ chat.title }}</div>
            <div class="history-item-date">{{ formatDate(chat.lastUpdated) }}</div>
            <el-dropdown
              trigger="click"
              @command="handleHistoryCommand($event, index)"
              class="history-actions"
            >
              <el-button type="primary" text size="small">
                <el-icon><MoreFilled /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="rename">重命名</el-dropdown-item>
                  <el-dropdown-item command="export">导出内容</el-dropdown-item>
                  <el-dropdown-item command="delete" divided>删除</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
          <div v-if="chatHistory.length === 0" class="empty-history">
            <el-empty description="暂无历史会话" :image-size="80">
              <el-button type="primary" @click="startNewChat">开始对话</el-button>
            </el-empty>
          </div>
        </div>
      </el-col>

      <!-- 中间部分 - 聊天区域 -->
      <el-col :span="14">
        <el-card class="chat-panel" shadow="never">
          <div class="chat-header">
            <div class="chat-title">
              <el-tag type="info" size="large" effect="plain">
                {{ currentChat.title }}
              </el-tag>
              <el-button
                type="primary"
                text
                class="edit-title-btn"
                @click="startEditingTitle"
                v-if="!isEditingTitle"
              >
                <el-icon><Edit /></el-icon>
              </el-button>
              <div v-else class="edit-title-input">
                <el-input
                  v-model="editingTitle"
                  size="small"
                  @blur="saveTitle"
                  @keyup.enter="saveTitle"
                  ref="titleInput"
                ></el-input>
              </div>
            </div>
            <div class="chat-actions">
              <el-tooltip content="导出当前会话" placement="top">
                <el-button type="primary" text @click="exportCurrentChat">
                  <el-icon><Download /></el-icon>
                </el-button>
              </el-tooltip>
              <el-tooltip content="清空当前会话" placement="top">
                <el-button type="danger" text @click="clearCurrentChat">
                  <el-icon><Delete /></el-icon>
                </el-button>
              </el-tooltip>
            </div>
          </div>

          <div class="messages-container" ref="messagesContainer">
            <div v-if="currentChat.messages.length === 0" class="welcome-message">
              <div class="assistant-avatar">
                <el-avatar :size="100" :src="assistantAvatar">🤖</el-avatar>
              </div>
              <h2>欢迎使用AI备课助手</h2>
              <p>您可以向我询问任何关于备课的问题，例如：</p>
              <div class="welcome-suggestions">
                <el-card
                  v-for="(suggestion, index) in welcomeSuggestions"
                  :key="index"
                  shadow="hover"
                  class="welcome-suggestion-item"
                  @click="applyMessage(suggestion)"
                >
                  <div class="suggestion-content">{{ suggestion }}</div>
                </el-card>
              </div>
            </div>

            <template v-else>
              <div
                v-for="(message, index) in currentChat.messages"
                :key="index"
                :class="['message', message.role]"
              >
                <div class="message-avatar">
                  <el-avatar
                    :size="40"
                    :src="message.role === 'assistant' ? assistantAvatar : userAvatar"
                  >
                    {{ message.role === 'assistant' ? '🤖' : '👤' }}
                  </el-avatar>
                </div>
                <div class="message-content">
                  <div class="message-header">
                    <span class="message-sender">
                      <el-tag
                        :type="message.role === 'assistant' ? 'primary' : 'success'"
                        size="small"
                      >
                        {{ message.role === 'assistant' ? 'AI助手' : '我' }}
                      </el-tag>
                    </span>
                    <span class="message-time">{{ formatTime(message.timestamp) }}</span>
                  </div>
                  <div class="message-body" v-html="formatMessageContent(message.content)"></div>
                  <div class="message-actions" v-if="message.role === 'assistant'">
                    <el-button
                      type="primary"
                      text
                      size="small"
                      @click="copyToClipboard(message.content)"
                    >
                      <el-icon><Document /></el-icon>复制
                    </el-button>
                    <el-button
                      type="primary"
                      text
                      size="small"
                      @click="saveToTeachingDesign(message.content)"
                    >
                      <el-icon><FolderAdd /></el-icon>保存到教案
                    </el-button>
                  </div>
                </div>
              </div>
              <div class="typing-indicator" v-if="isAITyping">
                <el-avatar :size="40" :src="assistantAvatar">🤖</el-avatar>
                <div class="typing-dots">
                  <span></span>
                  <span></span>
                  <span></span>
                </div>
              </div>
            </template>
            <div ref="messagesEnd"></div>
          </div>

          <div class="input-container">
            <div class="toolbar">
              <el-button-group>
                <el-tooltip content="上传文件" placement="top">
                  <el-button type="primary" text>
                    <el-icon><Upload /></el-icon>
                  </el-button>
                </el-tooltip>
                <el-tooltip content="插入图片" placement="top">
                  <el-button type="primary" text>
                    <el-icon><Picture /></el-icon>
                  </el-button>
                </el-tooltip>
                <el-tooltip content="语音输入" placement="top">
                  <el-button type="primary" text>
                    <el-icon><Microphone /></el-icon>
                  </el-button>
                </el-tooltip>
              </el-button-group>
            </div>
            <el-input
              v-model="userInput"
              type="textarea"
              :rows="3"
              placeholder="输入您的问题，Ctrl+Enter发送..."
              resize="none"
              @keydown.ctrl.enter="sendMessage"
              class="message-input"
            ></el-input>
            <div class="input-actions">
              <el-button
                :disabled="!userInput.trim()"
                type="primary"
                @click="sendMessage"
                size="large"
                :loading="isAITyping"
              >
                发送 <el-icon class="el-icon--right"><Position /></el-icon>
              </el-button>
            </div>
          </div>
        </el-card>
      </el-col>

      <!-- 右侧边栏 - 工具和建议 -->
      <el-col :span="6">
        <el-card class="tools-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <h3>备课工具箱</h3>
            </div>
          </template>
          <div class="tools-grid">
            <el-card
              v-for="(tool, index) in teachingTools"
              :key="index"
              shadow="hover"
              class="tool-item"
              @click="useTool(tool)"
              body-style="padding: 15px;"
            >
              <div class="tool-content">
                <el-icon size="24px" color="var(--el-color-primary)">
                  <component :is="tool.icon" />
                </el-icon>
                <span>{{ tool.name }}</span>
              </div>
            </el-card>
          </div>
        </el-card>

        <el-card class="suggestions-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <h3>备课建议</h3>
            </div>
          </template>
          <div class="suggestion-list">
            <el-card
              v-for="(suggestion, index) in promptSuggestions"
              :key="index"
              shadow="hover"
              class="suggestion-item"
              @click="applyMessage(suggestion.prompt)"
              body-style="padding: 15px;"
            >
              <div class="suggestion-content">
                <div class="suggestion-icon-title">
                  <el-icon size="20px" color="var(--el-color-primary)">
                    <component :is="suggestion.icon" />
                  </el-icon>
                  <div class="suggestion-title">{{ suggestion.title }}</div>
                </div>
                <div class="suggestion-desc">{{ suggestion.description }}</div>
              </div>
            </el-card>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 设置对话框 -->
    <el-dialog v-model="showSettingsDialog" title="AI助手设置" width="500px">
      <el-form label-position="top">
        <el-form-item label="AI助手风格">
          <el-radio-group v-model="aiSettings.style">
            <el-radio label="professional">专业严谨</el-radio>
            <el-radio label="friendly">友好活泼</el-radio>
            <el-radio label="concise">简洁明了</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="回答详细程度">
          <el-slider
            v-model="aiSettings.detailLevel"
            :min="1"
            :max="5"
            :marks="{ 1: '简略', 3: '适中', 5: '详细' }"
          />
        </el-form-item>
        <el-form-item label="备课偏好">
          <el-checkbox-group v-model="aiSettings.preferences">
            <el-checkbox label="includeExamples">包含教学案例</el-checkbox>
            <el-checkbox label="includeActivities">添加互动环节</el-checkbox>
            <el-checkbox label="includeReferences">引用教学参考</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showSettingsDialog = false">取消</el-button>
          <el-button type="primary" @click="saveSettings">保存设置</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, computed, onMounted, nextTick } from 'vue'
import {
  Plus,
  Setting,
  Edit,
  Download,
  Delete,
  Document,
  FolderAdd,
  Upload,
  Picture,
  Microphone,
  Position,
  MoreFilled,
} from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { format } from 'date-fns'

interface Message {
  role: 'user' | 'assistant'
  content: string
  timestamp: number
}

interface Chat {
  id: string
  title: string
  messages: Message[]
  lastUpdated: number
}

interface ToolItem {
  icon: string
  name: string
  action: string
}

interface PromptSuggestion {
  icon: string
  title: string
  description: string
  prompt: string
}

export default defineComponent({
  name: 'AIAssistantView',
  components: {
    Plus,
    Setting,
    Edit,
    Download,
    Delete,
    Document,
    FolderAdd,
    Upload,
    Picture,
    Microphone,
    Position,
    MoreFilled,
  },
  setup() {
    // 状态
    const showSettingsDialog = ref(false)
    const userInput = ref('')
    const isAITyping = ref(false)
    const chatHistory = ref<Chat[]>([])
    const currentChatIndex = ref(0)
    const isEditingTitle = ref(false)
    const editingTitle = ref('')
    const titleInput = ref<HTMLInputElement | null>(null)
    const messagesContainer = ref<HTMLElement | null>(null)
    const messagesEnd = ref<HTMLElement | null>(null)

    // 设置
    const aiSettings = ref({
      style: 'professional',
      detailLevel: 3,
      preferences: ['includeExamples', 'includeActivities'],
    })

    // 默认头像
    const userAvatar = ref('https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png')
    const assistantAvatar = ref(
      'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png',
    )

    // 欢迎建议
    const welcomeSuggestions = ref([
      '请帮我设计一节五年级数学分数乘法的课',
      '如何提高学生的课堂参与度？',
      '帮我整理一份初中语文课前预习材料',
      '设计一个有创意的历史课导入环节',
    ])

    // 备课工具箱
    const teachingTools = ref<ToolItem[]>([
      { icon: 'Document', name: '教案模板', action: 'template' },
      { icon: 'Compass', name: '课程设计', action: 'design' },
      { icon: 'PieChart', name: '课堂互动', action: 'interactive' },
      { icon: 'Clock', name: '时间规划', action: 'planning' },
      { icon: 'VideoPlay', name: '多媒体', action: 'multimedia' },
      { icon: 'Reading', name: '教学资源', action: 'resources' },
    ])

    // 备课建议
    const promptSuggestions = ref<PromptSuggestion[]>([
      {
        icon: 'Document',
        title: '教案设计',
        description: '获取专业教案设计和教学流程',
        prompt: '请帮我设计一节关于[主题]的课，包括教学目标、教学重难点和教学流程',
      },
      {
        icon: 'Compass',
        title: '教学策略',
        description: '探索多种教学方法和策略',
        prompt: '针对[主题]的教学，有哪些有效的教学策略和方法？',
      },
      {
        icon: 'PieChart',
        title: '课堂活动',
        description: '生成丰富多样的课堂互动活动',
        prompt: '请为[学科][年级]设计3-5个有趣的课堂互动活动',
      },
      {
        icon: 'Reading',
        title: '学习资源',
        description: '获取优质学习材料和资源推荐',
        prompt: '请推荐一些适合[年级]学生学习[主题]的优质资源和材料',
      },
    ])

    // 计算属性
    const currentChat = computed<Chat>(() => {
      if (chatHistory.value.length === 0) {
        // 返回一个新的空会话
        return {
          id: generateChatId(),
          title: '新会话',
          messages: [],
          lastUpdated: Date.now(),
        }
      }
      return chatHistory.value[currentChatIndex.value]
    })

    // 方法
    const generateChatId = () => {
      return `chat_${Date.now()}_${Math.floor(Math.random() * 1000)}`
    }

    const startNewChat = () => {
      const newChat: Chat = {
        id: generateChatId(),
        title: '新会话',
        messages: [],
        lastUpdated: Date.now(),
      }
      chatHistory.value.unshift(newChat)
      currentChatIndex.value = 0
      userInput.value = ''
    }

    const switchChat = (index: number) => {
      currentChatIndex.value = index
    }

    const formatDate = (timestamp: number) => {
      return format(new Date(timestamp), 'yyyy-MM-dd HH:mm')
    }

    const formatTime = (timestamp: number) => {
      return format(new Date(timestamp), 'HH:mm')
    }

    const formatMessageContent = (content: string) => {
      // 简单的Markdown格式化，可以根据需要扩展
      let formatted = content
        .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
        .replace(/\*(.*?)\*/g, '<em>$1</em>')
        .replace(/\n/g, '<br />')

      // 代码块处理
      formatted = formatted.replace(/```([\s\S]*?)```/g, '<pre><code>$1</code></pre>')

      // 列表处理
      formatted = formatted.replace(/^\s*-\s(.*$)/gm, '<li>$1</li>')
      formatted = formatted.replace(/(<li>.*<\/li>)/g, '<ul>$1</ul>')

      return formatted
    }

    const scrollToBottom = () => {
      nextTick(() => {
        if (messagesEnd.value) {
          messagesEnd.value.scrollIntoView({ behavior: 'smooth' })
        }
      })
    }

    const sendMessage = async () => {
      if (!userInput.value.trim()) return

      // 如果是新会话且没有消息，则用第一条消息内容更新标题
      if (currentChat.value.messages.length === 0) {
        const title =
          userInput.value.length > 20 ? userInput.value.substring(0, 20) + '...' : userInput.value
        currentChat.value.title = title
      }

      // 添加用户消息
      currentChat.value.messages.push({
        role: 'user',
        content: userInput.value,
        timestamp: Date.now(),
      })

      // 更新最后更新时间
      currentChat.value.lastUpdated = Date.now()

      // 清空输入并滚动到底部
      const userMessage = userInput.value
      userInput.value = ''
      scrollToBottom()

      // 模拟AI思考
      isAITyping.value = true

      // 这里应该调用实际的AI API，这里仅做模拟
      setTimeout(() => {
        isAITyping.value = false

        // 模拟AI回复
        currentChat.value.messages.push({
          role: 'assistant',
          content: `这是对"${userMessage}"的AI回复。实际应用中，这里应该是从API获取的回复内容。`,
          timestamp: Date.now(),
        })

        // 保存到本地存储
        saveChatsToLocalStorage()
        scrollToBottom()
      }, 1500)
    }

    const saveChatsToLocalStorage = () => {
      try {
        localStorage.setItem('aiAssistantChats', JSON.stringify(chatHistory.value))
      } catch (error) {
        console.error('保存会话历史失败:', error)
      }
    }

    const loadChatsFromLocalStorage = () => {
      try {
        const savedChats = localStorage.getItem('aiAssistantChats')
        if (savedChats) {
          chatHistory.value = JSON.parse(savedChats)
          if (chatHistory.value.length > 0) {
            currentChatIndex.value = 0
          }
        }
      } catch (error) {
        console.error('加载会话历史失败:', error)
      }
    }

    const startEditingTitle = () => {
      editingTitle.value = currentChat.value.title
      isEditingTitle.value = true
      nextTick(() => {
        if (titleInput.value) {
          titleInput.value.focus()
        }
      })
    }

    const saveTitle = () => {
      if (editingTitle.value.trim()) {
        currentChat.value.title = editingTitle.value
        saveChatsToLocalStorage()
      }
      isEditingTitle.value = false
    }

    const handleHistoryCommand = (command: string, index: number) => {
      switch (command) {
        case 'rename':
          currentChatIndex.value = index
          startEditingTitle()
          break
        case 'export':
          exportChat(chatHistory.value[index])
          break
        case 'delete':
          deleteChat(index)
          break
      }
    }

    const exportChat = (chat: Chat) => {
      try {
        // 创建导出文本
        let exportText = `# ${chat.title}\n`
        exportText += `导出时间: ${formatDate(Date.now())}\n\n`

        chat.messages.forEach((msg) => {
          exportText += `## ${msg.role === 'assistant' ? 'AI助手' : '用户'} (${formatDate(msg.timestamp)})\n`
          exportText += `${msg.content}\n\n`
        })

        // 创建Blob对象
        const blob = new Blob([exportText], { type: 'text/plain;charset=utf-8' })

        // 创建下载链接
        const url = URL.createObjectURL(blob)
        const link = document.createElement('a')
        link.href = url
        link.download = `${chat.title}.txt`

        // 触发下载
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        URL.revokeObjectURL(url)

        ElMessage.success('导出成功')
      } catch (error) {
        console.error('导出会话失败:', error)
        ElMessage.error('导出失败')
      }
    }

    const exportCurrentChat = () => {
      exportChat(currentChat.value)
    }

    const deleteChat = (index: number) => {
      chatHistory.value.splice(index, 1)
      if (currentChatIndex.value >= chatHistory.value.length) {
        currentChatIndex.value = Math.max(0, chatHistory.value.length - 1)
      }
      saveChatsToLocalStorage()
    }

    const clearCurrentChat = () => {
      currentChat.value.messages = []
      saveChatsToLocalStorage()
    }

    const copyToClipboard = (text: string) => {
      navigator.clipboard
        .writeText(text)
        .then(() => ElMessage.success('已复制到剪贴板'))
        .catch(() => ElMessage.error('复制失败'))
    }

    const saveToTeachingDesign = (content: string) => {
      // 这里应该实现保存到教案的功能
      ElMessage.success('已保存到教案')
    }

    const applyMessage = (message: string) => {
      userInput.value = message
    }

    const useTool = (tool: ToolItem) => {
      // 这里应该实现工具的功能
      ElMessage.info(`即将使用工具: ${tool.name}`)
    }

    const saveSettings = () => {
      // 保存设置到本地存储
      localStorage.setItem('aiAssistantSettings', JSON.stringify(aiSettings.value))
      showSettingsDialog.value = false
      ElMessage.success('设置已保存')
    }

    // 生命周期钩子
    onMounted(() => {
      loadChatsFromLocalStorage()

      // 如果没有会话历史，创建一个新会话
      if (chatHistory.value.length === 0) {
        startNewChat()
      }

      // 加载设置
      try {
        const savedSettings = localStorage.getItem('aiAssistantSettings')
        if (savedSettings) {
          aiSettings.value = JSON.parse(savedSettings)
        }
      } catch (error) {
        console.error('加载设置失败:', error)
      }
    })

    return {
      showSettingsDialog,
      userInput,
      isAITyping,
      chatHistory,
      currentChatIndex,
      currentChat,
      isEditingTitle,
      editingTitle,
      titleInput,
      messagesContainer,
      messagesEnd,
      aiSettings,
      userAvatar,
      assistantAvatar,
      welcomeSuggestions,
      teachingTools,
      promptSuggestions,
      startNewChat,
      switchChat,
      formatDate,
      formatTime,
      formatMessageContent,
      sendMessage,
      startEditingTitle,
      saveTitle,
      handleHistoryCommand,
      exportCurrentChat,
      clearCurrentChat,
      copyToClipboard,
      saveToTeachingDesign,
      applyMessage,
      useTool,
      saveSettings,
    }
  },
})
</script>

<style scoped>
.ai-assistant-container {
  padding: 20px;
  height: calc(100vh - 60px);
  display: flex;
  flex-direction: column;
  background-color: #f5f7fa;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 0 10px;

  .header-left h1 {
    margin: 0;
    font-size: 24px;
    color: var(--el-color-primary);
    font-weight: 600;
  }

  .subtitle {
    margin: 5px 0 0;
    color: #606266;
    font-size: 14px;
  }
}

.main-content {
  flex: 1;
  overflow: hidden;
}

.sidebar {
  height: calc(100vh - 140px);
  padding-right: 10px;

  .sidebar-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 10px;
    margin-bottom: 10px;

    h3 {
      margin: 0;
      font-size: 16px;
      font-weight: 500;
    }
  }

  .history-list {
    height: calc(100% - 40px);
    overflow-y: auto;
    padding: 5px;

    .history-item {
      padding: 12px 10px;
      margin: 5px 0;
      border-radius: 8px;
      cursor: pointer;
      position: relative;
      transition: all 0.3s;
      background-color: #fff;
      box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);

      &:hover {
        background-color: #f0f7ff;
        box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
      }

      &.active {
        background-color: #e6f1ff;
        border-left: 3px solid var(--el-color-primary);
      }

      .history-item-title {
        font-weight: 500;
        margin-bottom: 5px;
        padding-right: 30px;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
      }

      .history-item-date {
        font-size: 12px;
        color: #909399;
      }

      .history-actions {
        position: absolute;
        right: 5px;
        top: 10px;
      }
    }

    .empty-history {
      text-align: center;
      padding: 20px;
      color: #909399;
      background-color: #fff;
      border-radius: 8px;
      margin-top: 10px;
    }
  }
}

.chat-panel {
  height: calc(100vh - 140px);
  display: flex;
  flex-direction: column;
  border-radius: 8px;
  overflow: hidden;

  .chat-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10px 20px;
    background-color: #fff;
    border-bottom: 1px solid #ebeef5;
    z-index: 1;

    .chat-title {
      display: flex;
      align-items: center;
      gap: 10px;
    }

    .edit-title-input {
      width: 200px;
    }
  }

  .messages-container {
    flex: 1;
    overflow-y: auto;
    padding: 20px;
    background-color: #f9fafc;

    .welcome-message {
      text-align: center;
      padding: 40px 20px;
      max-width: 800px;
      margin: 0 auto;

      .assistant-avatar {
        margin-bottom: 20px;
      }

      h2 {
        margin-bottom: 10px;
        color: var(--el-color-primary);
      }

      p {
        color: #606266;
        margin-bottom: 20px;
      }

      .welcome-suggestions {
        display: grid;
        grid-template-columns: repeat(2, 1fr);
        gap: 15px;
        margin-top: 30px;

        .welcome-suggestion-item {
          cursor: pointer;
          transition: all 0.3s;
          height: 100%;

          &:hover {
            transform: translateY(-3px);
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
          }

          .suggestion-content {
            padding: 10px;
            text-align: left;
          }
        }
      }
    }

    .message {
      display: flex;
      margin-bottom: 20px;
      max-width: 90%;

      &.user {
        flex-direction: row-reverse;
        margin-left: auto;
      }

      &.assistant {
        margin-right: auto;
      }

      .message-avatar {
        margin: 0 15px;
      }

      .message-content {
        max-width: calc(100% - 70px);
        border-radius: 12px;
        padding: 12px 16px;
        background-color: #fff;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
        position: relative;

        &::before {
          content: '';
          position: absolute;
          top: 15px;
          width: 0;
          height: 0;
          border: 8px solid transparent;
        }
      }

      &.user .message-content {
        background-color: var(--el-color-primary-light-9);
        border-top-right-radius: 0;

        &::before {
          right: -16px;
          border-left-color: var(--el-color-primary-light-9);
        }
      }

      &.assistant .message-content {
        background-color: #fff;
        border-top-left-radius: 0;

        &::before {
          left: -16px;
          border-right-color: #fff;
        }
      }

      .message-header {
        display: flex;
        justify-content: space-between;
        margin-bottom: 8px;
        font-size: 12px;
        align-items: center;
      }

      .message-sender {
        font-weight: 500;
      }

      .message-time {
        color: #909399;
        margin-left: 10px;
      }

      .message-body {
        line-height: 1.6;
        color: #303133;

        pre {
          background-color: #f5f7fa;
          padding: 12px;
          border-radius: 6px;
          overflow-x: auto;
          font-family: 'Courier New', Courier, monospace;
          margin: 8px 0;
        }

        code {
          font-family: 'Courier New', Courier, monospace;
          background-color: #f5f7fa;
          padding: 2px 4px;
          border-radius: 3px;
          font-size: 0.9em;
        }

        ul,
        ol {
          padding-left: 20px;
          margin: 8px 0;
        }

        li {
          margin-bottom: 4px;
        }

        strong {
          font-weight: 600;
        }

        em {
          font-style: italic;
        }
      }

      .message-actions {
        margin-top: 10px;
        display: flex;
        justify-content: flex-end;
        gap: 5px;
      }
    }

    .typing-indicator {
      display: flex;
      align-items: center;
      gap: 15px;
      padding: 12px 20px;
      background-color: #fff;
      border-radius: 12px;
      width: fit-content;
      margin-bottom: 20px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);

      .typing-dots {
        display: flex;
        gap: 5px;

        span {
          width: 8px;
          height: 8px;
          background-color: var(--el-color-primary);
          border-radius: 50%;
          opacity: 0.6;
          animation: typing 1.4s infinite both;
        }

        span:nth-child(2) {
          animation-delay: 0.2s;
        }

        span:nth-child(3) {
          animation-delay: 0.4s;
        }
      }
    }
  }

  .input-container {
    padding: 15px 20px;
    background-color: #fff;
    border-top: 1px solid #ebeef5;

    .toolbar {
      margin-bottom: 10px;
    }

    .message-input {
      :deep(.el-textarea__inner) {
        border-radius: 8px;
        padding: 12px 15px;
        box-shadow: none;
        border: 1px solid #dcdfe6;
        transition: all 0.3s;

        &:focus {
          border-color: var(--el-color-primary);
          box-shadow: 0 0 0 2px var(--el-color-primary-light-5);
        }
      }
    }

    .input-actions {
      display: flex;
      justify-content: flex-end;
      margin-top: 10px;
    }
  }
}

.tools-card,
.suggestions-card {
  margin-bottom: 20px;
  border-radius: 8px;

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;

    h3 {
      margin: 0;
      font-size: 16px;
      font-weight: 500;
    }
  }

  .tools-grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 12px;

    .tool-item {
      cursor: pointer;
      transition: all 0.3s;

      &:hover {
        transform: translateY(-3px);
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
      }

      .tool-content {
        display: flex;
        flex-direction: column;
        align-items: center;
        gap: 8px;
      }
    }
  }

  .suggestion-list {
    display: flex;
    flex-direction: column;
    gap: 12px;

    .suggestion-item {
      cursor: pointer;
      transition: all 0.3s;

      &:hover {
        transform: translateY(-3px);
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
      }

      .suggestion-content {
        .suggestion-icon-title {
          display: flex;
          align-items: center;
          gap: 10px;
          margin-bottom: 8px;

          .suggestion-title {
            font-weight: 500;
          }
        }

        .suggestion-desc {
          font-size: 12px;
          color: #606266;
          line-height: 1.4;
        }
      }
    }
  }
}

@keyframes typing {
  0% {
    opacity: 0.6;
    transform: translateY(0);
  }
  50% {
    opacity: 1;
    transform: translateY(-3px);
  }
  100% {
    opacity: 0.6;
    transform: translateY(0);
  }
}
</style>
